'use strict';

const Controller = require('egg').Controller;


class ListController extends Controller {
    // 初始化数据接口
    async index() {
        const { ctx } = this;
        const data= await this.app.mysql.select('mylist');
        if(data){
            ctx.body={
                code:200,
                mes:'查询成功',
                data
            }
        }else{
            ctx.body={
                code:402,
                mes:'查询失败'
            }
        }
    }
    async addList(){
        const { ctx } = this;
        const {title,detail,tips}=ctx.request.body;
        let sql=`INSERT INTO mylist (title, detail, tips, id) VALUES ('${title}', '${detail}', '${tips}', NULL)`
        const isAdd=await this.app.mysql.query(sql)
        if(isAdd.affectedRows){
            ctx.body={
                code:200,
                mes:'添加成功'
            }
        }else{
            ctx.body={
                code:203,
                mes:'添加失败'
            }
        }

    }
    // 修改数据
    async editList(){
        const { ctx } = this;
        const {title,detail,tips,id}=ctx.request.body
        let sql=`UPDATE mylist SET title = '${title}', detail = '${detail}', tips = '${tips}' WHERE mylist.id = ${id}`
        const isEdit = await this.app.mysql.query(sql)
        if(isEdit.affectedRows){
            ctx.body={
                code:200,
                mes:'修改成功'
            }
        }else{
            ctx.body={
                code:203,
                mes:'修改失败'
            }
        }
    }
    //删除数据
    async delList(){
        const { ctx } = this;
        const {id}=ctx.query;
        let sql=`DELETE FROM mylist WHERE mylist.id = ${id}`
        const isDel = await this.app.mysql.query(sql)
        if(isDel.affectedRows){
            ctx.body={
                code:200,
                mes:'删除成功'
            }
        }else{
            ctx.body={
                code:203,
                mes:'删除失败'
            }
        }

    }
}

module.exports = ListController;

